package lib.modules;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import lib.base.EgoCalendar;
import lib.base.EgoModule;
import lib.data.Customer;
import lib.data.Department;
import lib.data.Employee;

public class ModRegister extends EgoModule {

	public ModRegister(HttpServletRequest req)
	{
		super(req);
		req.getSession().setAttribute("template", "modules/register/index.jsp");
	}

	@Override
	public void work() throws Exception
	{
		if (_request.getParameter("action") != null)
		{
			if (_request.getParameter("action").equals( "reg" ))
			{
				_register();
			} else if (_request.getParameter("action").equals( "check" ))
			{
				_check();
			}
		}
		_request.setAttribute("email", _request.getSession().getAttribute("email"));
	}
	
	private void _check() throws Exception
	{
		boolean w = EgoCalendar.checkCredentials(
			_request.getParameter("systemAccount").toString()
			, _request.getParameter("pwd").toString()
		);
		_request.setAttribute("ajax_return", String.valueOf(w));
		_request.getSession().setAttribute("template", "ajax_return.jsp");
	}
	
	private void _register() throws Exception
	{
		// first create new customer
		Customer cust = Customer.newCustomer(
			_request.getSession().getAttribute("email").toString()
			, null
		);
		
		// then create the default department
		Department dep = Department.newDepartment(cust);
		dep.setField(
			"name"
			, _request.getParameter("dep").toString()
		);
		dep.update();
		
		// create employee with current user
		Employee emp = Employee.newEmployee(cust);
		emp.setField(
			"account"
			, _request.getSession().getAttribute("email").toString()
		);
		emp.setField(
			"givenName"
			, _request.getParameter("gn").toString()
		);
		emp.setField(
			"lastName"
			, _request.getParameter("ln").toString()
		);
		emp.setField(
			"isAdmin"
			, "1"
		);
		emp.update();

		cust.update();

		// add this employee to default department
		dep.addEmployee(emp, "supervisor");

		cust.refresh();
		
		// at least setup the google calendar
		ArrayList<Employee> emps = cust.getAllEmployees();
		for (int i=0; i<emps.size(); i++)
		{
			cust.holidayManager.setupCalendar(emps.get(i));
		}
		ArrayList<Department> deps = cust.getAllDepartments();
		for (int i=0; i<deps.size(); i++)
		{
			cust.holidayManager.setupCalendar(deps.get(i));
		}

		_request.getSession().setAttribute("template", "ajax_return.jsp");
	}
}
